package cn.fcj.f20240328.fsocket.server;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

import cn.fcj.f20240328.fsocket.ReadDataEntity;
import cn.fcj.f20240328.fsocket.base.FBaseNIOSocket;

/**
 * @项目名称:FSocket
 * @功能描述:多selector处理
 * @开发　者:mochhk
 * @邮　　箱:mochhk@163.com
 * @CreateDate:2024/3/29 20:31
 */
public class SelectorThread extends FBaseNIOSocket<SocketChannel> {
    @Override
    public void initSocket() throws IOException {
        mSelector = Selector.open();
    }
    public void wakeup(){
        mSelector.wakeup();
    }
    /**
     * 处理selector 的阻塞问题,重写父类方法
     * @return
     * @throws IOException
     */
    public int select() throws IOException {
        if(isRegistering){
//            System.out.println("-------------多线程事件处理运行中----注册时--wait()---------");
            return -1;
        }
        return mSelector.select(100);
    }

    @Override
    public void connectionHandler(SelectionKey key) throws IOException {

    }

    @Override
    public void exceptionHandler(Exception e, ErrorCode errorCode, SelectionKey key) {
        super.exceptionHandler(e, errorCode, key);
        if(errorCode==ErrorCode.SOCKET_DISCONNECT){
            disConnect(key);
        }
    }

    /**
     * 有连接断开时，处理断开信息
     * @param key
     */
    private void disConnect(SelectionKey key){
        if(key!=null){
            try {
                key.cancel();
                SocketChannel channel=(SocketChannel)key.channel();
                System.out.println("-------------多线程事件处理运行中-------连接断开---------"+channel.getRemoteAddress().toString());
                if(!FNIOSocketServer.clients.isEmpty()){
                    FNIOSocketServer.clients.remove(ReadDataEntity.getChannelIP(channel));
                }
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
